const mysql = require('mysql')
const xss = require('xss')
const { isObject } = require('./util')

const MYSQL_CONF = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  port: '3306',
  database: 'ipackage'
}

const sqlConnect = mysql.createConnection(MYSQL_CONF)
sqlConnect.connect()
const escape = mysql.escape

const sqlEscape = (val) => {
  if (isObject(val)) {
    for (let key in val) {
      val[key] = escape(xss(val[key]))
    }
  } 
  else if (Array.isArray(val)) {
    val = val.map((item) => escape(xss(item)))
  }
  else {
    val = escape(xss(val))
  }
  return val
}

module.exports = {
  executeSql: (sql) => (
    new Promise((resolve, reject) => {
      sqlConnect.query(sql, (err, result) => {
        if (err) {
          console.log(err)
          reject()
          return
        }
        resolve(result)
      })
    })       
  ),
  sqlEscape
}